package com.wk.springbootlearn.controller;

import com.wk.springbootlearn.common.model.Response;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

@Api(value = "文件上传", tags = "文件处理模块")
@RestController
@RequestMapping("/file")
public class FileUploadController {

    @PostMapping("/upload")
    public Response fileUpload(@RequestParam("files") MultipartFile[] files) {
        String property = System.getProperty("user.dir");
        File propertyFile = new File(property);
        String fileRootPath = propertyFile.getPath() + File.separator + "public" + File.separator;
        String filePath = "";
        HashMap<String, ArrayList> resData = new HashMap<>();
        ArrayList<String> resList = new ArrayList<>();
        // 多文件上传
        for (MultipartFile file : files) {
            String originalFilename = file.getOriginalFilename();
            // 存储路径
            long timer = System.currentTimeMillis();
            filePath = fileRootPath + timer + originalFilename;

            try{
                File f = new File(filePath);
                f.mkdirs();
                // 保存文件
                file.transferTo(f);
                resList.add("http://127.0.0.1:8080/file/" + timer + originalFilename);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        resData.put("url", resList);
        return new Response().setData(resData);
    }
}
